# 导入需要的包
import json

import requests  # 网络请求
import base64


class SpiderHaiJiaoSheQu:
    # 初始化
    def __init__(self):
        self.__Domain = "https://www.hj87d29.top/"
        self.__headers = {
            'user-agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1',
        }
    
    # 海角数据加密破解函数
    def __HaiJiaoEncryptionCracking(self, EncryptionData: str) -> list:
        global encodestr
        for i in range(3):
            if i == 0:
                encodestr = base64.b64decode(EncryptionData)
            else:
                encodestr = base64.b64decode(encodestr)
        return json.loads(encodestr.decode())
    
    # 获取帖子数据
    def GetHaiJiaoNewsList(self, Page=1, BanKuaiId=1):
        Params = {
            "page": Page
        }
        ApiUrl = ""
        # 板块的api链接
        BanKuaiUrlList = [
            "api/topic/hot/topics",  # 首页
            "api/topic/node/news"  # 新闻
        ]
        if BanKuaiId == 1:
            ApiUrl = BanKuaiUrlList[0]
        elif BanKuaiId == 2:
            ApiUrl = BanKuaiUrlList[1]
        else:
            return []
        response = requests.get(url=self.__Domain + ApiUrl, headers=self.__headers, params=Params).json()
        data = self.__HaiJiaoEncryptionCracking(response['data'])
        return data
    
    # 获取帖子详情数据
    def GetHaiJiaoNewsInfo(self, Pid):
        SpiderUrl = self.__Domain + f"api/topic/{Pid}"
        response = requests.get(url=SpiderUrl, headers=self.__headers).json()
        data = self.__HaiJiaoEncryptionCracking(EncryptionData=response['data'])
        return data
    
    # 获取帖子的评论
    def GetHaiJiaoCommit(self, Pid, Page=1):
        SpiderUrl = self.__Domain + f"api/comment/reply_list"
        Params = {
            "page": Page,
            "sort": "asc",
            "topic_id": Pid,
            "search_type": 0,
            "user_id": 0
        }
        response = requests.get(url=SpiderUrl, headers=self.__headers, params=Params).json()
        data = self.__HaiJiaoEncryptionCracking(response['data'])
        return data
    
    # 搜索
    def GetHaiJiaoSearch(self, SearchText, Page=1):
        SpiderUrl = self.__Domain + "api/topic/search"
        Params = {
            "key": SearchText,
            "node_id": 0,
            "page": Page
        }
        response = requests.post(url=SpiderUrl, headers=self.__headers, data=Params).json()
        data = self.__HaiJiaoEncryptionCracking(response['data'])
        return data


if __name__ == '__main__':
    Sp = SpiderHaiJiaoSheQu()
    a = Sp.GetHaiJiaoNewsList(Page=1, BanKuaiId=1)
    print(a)
